package com.ssm.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ssm.model.LoginInfo;
import com.ssm.service.LoginService;

/**
 * Created by myx on 2018/1/10.
 */


@Component
public class LoginRealm extends AuthorizingRealm {
    @Autowired
    private LoginService loginService;

    /**
     * 获取身份信息，我们可以在这个方法中，从数据库获取该用户的权限和角色信息
     *     当调用权限验证时，就会调用此方法
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1、从principalCollection中获取当前登陆用户信息
        LoginInfo loginInfo = (LoginInfo) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(loginService.findRoles(loginInfo.getLoginId().toString()));
        System.out.println(">>>>>>>AuthorizationInfo>>>>>>>"+info.getRoles());
        return info;
    }

    /**
     * 在这个方法中，进行身份验证
     *         login时调用
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken uToken = (UsernamePasswordToken)authenticationToken;
        String username = uToken.getUsername();
        String password = new String((char[])uToken.getCredentials());
        LoginInfo loginInfo = null;
        try{
            loginInfo = loginService.selectByUserName(username);
        }catch (Exception e){
            e.printStackTrace();
        }
        if (loginInfo == null) {
            //没有该用户名
            throw new UnknownAccountException();
        } else if (!password.equals(loginInfo.getPassword())) {
            //密码错误
            throw new IncorrectCredentialsException();
        }
        //身份验证通过，返回一个身份信息
        AuthenticationInfo info = new SimpleAuthenticationInfo(loginInfo,password,getName());

        return info;
    }
}
